//
//  MusicPlayerController.m
//  musicPlayer
//
//  Created by sxiaojian on 14-9-10.
//  Copyright (c) 2014年 sxiaojian. All rights reserved.
//

#import "MusicPlayerController.h"
#import "customSlider.h"
#import "STKAudioPlayer.h"
#import "STKAutoRecoveringHTTPDataSource.h"
#import "AudioQueueId.h"
#import <AVFoundation/AVFoundation.h>
#import "JingRoundView.h"
#define animationDur  0.5
#import <MediaPlayer/MediaPlayer.h>
#import "SDWebImage/UIImageView+WebCache.h"
#define FMRFRadioViewSetSongInformationNotification @"FMRFRadioViewSetSongInformationNotification"
#define FMRFRadioViewStatusNotifiation  @"FMRFRadioViewStatusNotifiation"
@interface MusicPlayerController ()
{
    UIButton *playButton;

    NSTimer* timer;
}
@property (strong, nonatomic) IBOutlet UIView *needleImageView;
@property (strong, nonatomic) IBOutlet JingRoundView *roundView;
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
@property (strong, nonatomic) IBOutlet customSlider *mySlider;
- (IBAction)sliderClicked:(id)sender;

- (IBAction)sliderValueChanged:(customSlider *)sender;
@end

@implementation MusicPlayerController

+(MusicPlayerController *)shareMusicViewController
{
    
    static MusicPlayerController *player ;
    if (player == nil) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        player =[storyboard instantiateViewControllerWithIdentifier:@"player"];
        [player setupAudio];
    }
    return player;

}
-(void)setupAudio
{
    NSError* error;
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    
    Float32 bufferLength = 0.1;
    AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof(bufferLength), &bufferLength);
    self.audioPlayer = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = NO, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.audioPlayer.meteringEnabled = YES;
    self.audioPlayer.volume = 1;
    
}
-(void)setupSlider
{
    self.mySlider.minimumValue = 0;
    self.mySlider.maximumValue = [self.originalDic[@"file_duration"] intValue]?[self.originalDic[@"file_duration"] intValue]:1;
    self.mySlider.value = 0;
    [self.mySlider setMaxTrackImageName:@"cm_btn_btm_oval_prs" MinTrackImageName:@"cm_btn" thumbImageName:@"cm_trcl_paly" LeftCapWidth:25 topCapHeight:15 thumbNextImage:@"cm_trcl_pause" thumbHighLightImage:@"cm_trcl_drag_prs"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSlider];
    [self setupTimer];
    self.roundView.roundImage = [UIImage imageNamed:@"girl"];
    self.roundView.delegate = self;
    self.roundView.isPlay = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackgroundSetSongInformation:) name:FMRFRadioViewSetSongInformationNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackgroundControlRadioStatus:) name:FMRFRadioViewStatusNotifiation object:nil];
    
}
-(void)setSongUrl:(NSString *)songUrl
{
    if ([_songUrl isEqualToString:songUrl]) {
        return;
    }
    _songUrl = songUrl;
    [self.audioPlayer stop];
    [self performSelector:@selector(playWithUrl:) withObject:songUrl afterDelay:0];
}
-(void)applicationDidEnterBackgroundSetSongInformation:(NSNotification *)notification
{
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
        UIImageView *imageview = [[UIImageView alloc] init];
        [imageview sd_setImageWithURL:[NSURL URLWithString:_originalDic[@"pic_big"]]];
        [dict setObject:_originalDic[@"title"] forKey:MPMediaItemPropertyTitle];
        [dict setObject:_originalDic[@"author"]  forKey:MPMediaItemPropertyArtist];
        		[dict setObject:[[MPMediaItemArtwork alloc] initWithImage:imageview.image] forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}
-(void)applicationDidEnterBackgroundControlRadioStatus:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
    NSString * string = [dict objectForKey:@"keyStatus"];
    if ([string isEqualToString:@"UIEventSubtypeRemoteControlPause"]) {
        [self playButtonPressed];
    }else if ([string isEqualToString:@"UIEventSubtypeRemoteControlPlay"]){
        [self playButtonPressed];
    }else if ([string isEqualToString:@"UIEventSubtypeRemoteControlPreviousTrack"]){
//        [self preButtonEvent:_preButton];
    }else if ([string isEqualToString:@"UIEventSubtypeRemoteControlNextTrack"]){
//        [self nextButtonEvent:_nextButton];
    }
}
-(void)setOriginalDic:(NSDictionary *)originalDic
{
    _originalDic = originalDic;
}
-(void) setupTimer
{
    timer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(tick) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)playWithUrl:(NSString *)url
{
    NSURL *URL = [NSURL URLWithString:url];
    STKDataSource* dataSource = [STKAudioPlayer dataSourceFromURL:URL];
    
    [self.audioPlayer queueDataSource:dataSource withQueueItemId:[[AudioQueueId alloc] initWithUrl:URL andCount:0]];
}
-(void) tick
{
    
    if (self.audioPlayer.duration != 0)
    {
        self.mySlider.value = self.audioPlayer.progress;
        
        self.timeLabel.text = [NSString stringWithFormat:@"%@ - %@", [self formatTimeFromSeconds:self.audioPlayer.progress], [self formatTimeFromSeconds:self.audioPlayer.duration]];
    }

}
-(NSString*) formatTimeFromSeconds:(int)totalSeconds
{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
-(void) stopButtonPressed
{
    [_audioPlayer stop];
}
-(void) playButtonPressed
{
    if (!self.audioPlayer)
    {
        return;
    }
    
    if (self.audioPlayer.state == STKAudioPlayerStatePaused)
    {
        
        [self performSelector:@selector(roundPlay) withObject:nil afterDelay:animationDur];
        [self discPlay];
    }
    else
    {
        [self.audioPlayer pause];
        [self roundPause];
        [self discPause];
    }
}
-(void)discPlay
{
    //Rotation
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = [NSNumber numberWithFloat:-M_PI / 12.0];
    rotationAnimation.toValue = [NSNumber numberWithFloat: 0 ];
    
    //default RotationDuration value
    
    
    rotationAnimation.duration = animationDur;
    rotationAnimation.RepeatCount = 1;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO; //No Remove
    rotationAnimation.fillMode = kCAFillModeForwards;
    [self.needleImageView.layer addAnimation:rotationAnimation forKey:@"rotation"];
}
-(void)discPause
{
    //Rotation
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.fromValue = [NSNumber numberWithFloat:0];
    rotationAnimation.toValue = [NSNumber numberWithFloat: -M_PI / 12.0 ];
    
    //default RotationDuration value

    rotationAnimation.duration = animationDur;
    rotationAnimation.RepeatCount = 1;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO; //No Remove
    rotationAnimation.fillMode = kCAFillModeForwards;
    [self.needleImageView.layer addAnimation:rotationAnimation forKey:@"rotation"];
    

}

-(void)roundPlay
{
//    [self performSelector:@selector(roundPlayFunc) withObject:nil afterDelay:animationDur];
    [self.audioPlayer resume];
    [self roundPlayFunc];
   
}
-(void)roundPlayFunc
{
    self.roundView.isPlay = YES;
  
}
-(void)roundPause
{
    self.roundView.isPlay = NO;
}
-(void) playStatuUpdate:(BOOL)playState
{
    [self playButtonPressed];
    [self.mySlider changeByother];
}
- (IBAction)sliderClicked:(id)sender {
    [self playButtonPressed];
}

- (IBAction)sliderValueChanged:(customSlider *)sender {
    if (!self.audioPlayer)
    {
        return;
    }
    
    NSLog(@"Slider Changed: %f", self.mySlider.value);
    
    [self.audioPlayer seekToTime:self.mySlider.value];
}

@end
